package com.adm.biz;

import java.lang.reflect.Method;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.yfsoft.comm.util.BizResult;
import org.yfsoft.comm.util.StringUtil;

import com.adm.ctl.GlobalKey;
import com.adm.ctl.ResultType;
import com.adm.dao.CommonDao;

public abstract class Service {

	protected Service (){}
	
	protected HttpServletRequest request = null;
	
	protected HttpServletResponse response = null;
	
	public abstract void setDao(CommonDao dao);
	
	private Map<String,String> input = null;
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	protected final void reflect(String o) throws Throwable{
		Class cls = this.getClass();
		Method m = cls.getMethod(o, Map.class);
		Object rst = m.invoke(this, this.input);
		forward((BizResult)rst);
	}
	
	public void execute(Map<String,String> input,HttpServletRequest request, HttpServletResponse response)
		throws Throwable{
		this.request = request;
		this.response = response;
		this.input = input;
		String o = input.get("o");
		if(!StringUtil.isNullOrEmpty(o)){this.input.remove("o"); reflect(o);}
		//TODO....
	}
	
	protected final void forward(BizResult rst) throws Throwable{
		
		if(!"0".equals(rst.getCode())){response.getWriter().print(rst.getMsg()); }
		String t = rst.getType();
		if(StringUtil.isNullOrEmpty(t)){response.getWriter().print(rst.getData());}
		switch(Byte.parseByte(t)){
		case ResultType.JUMP:
			response.sendRedirect(rst.getPage());
			return;
		case ResultType.REDIRECT:
			request.setAttribute(GlobalKey.BIZ_RESULT, rst);
			request.getRequestDispatcher(rst.getPage()).forward(request, response);
			return;	
			
		}
		response.getWriter().print(rst.getData());
	}
	
	protected final void setReqAttr(String key,Object o){
		request.setAttribute(key, o);
	}
	
	protected final void setSionAttr(String key,Object o){
		request.getSession().setAttribute(key, o);
	}
	
	protected final void unsetSion(String key){
		request.getSession().removeAttribute(key);
	}
	
	
}
